<template>
  <div class="app-container">

    <!-- <h2>
      {{textMap[dialogStatus]}}
    </h2> -->

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <el-table
        :data="baseInfo"
        style="width: 100%">
        <el-table-column label="单位名称" width="180">
          <template slot-scope="scope">
            <span>{{scope.row.company || '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系人姓名" width="140">
          <template slot-scope="scope">
            <span>{{scope.row.username || '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系电话"  width="140">
          <template slot-scope="scope">
            <span>{{scope.row.telephone || '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="所在区域" width="180">
          <template slot-scope="scope">
            <span>{{scope.row.adminstrative || '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位地址"  min-width="120">
          <template slot-scope="scope">
            <span>{{scope.row.address || '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template slot-scope="scope">
            <span>已接入</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div style="float:right;">
          <el-button @click="goBack" :loading="btnLoading">返回</el-button>
          <el-button type="success" @click="handleCreate" :loading="btnLoading" plain icon="el-icon-plus">添加新测点</el-button>
        </div>
        <span>点选测点</span>
      </div>
      <div>
        <el-radio-group v-model="handleDeviceId" @change="changeDeviceId">
          <template v-for="(item, index) in deviceList">
            <el-radio :label="item.deviceMac" :key="index">{{item.deviceName}}</el-radio>
          </template>
        </el-radio-group>
      </div>
    </el-card>
    
    <template v-if="deviceList.length > 0">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>测点信息</span>
        </div>
        <el-form 
          v-loading="tempUpdateLoading"
          :rules="rules" 
          ref="dataFormUpdate" 
          :model="tempUpdate" 
          label-width="140px" 
          style='width:100%;'
          class="up-card clearfix"
        >

          <el-form-item label="测点MAC：" prop="deviceMac">
            <el-input v-model="tempUpdate.deviceMac" placeholder="请填写测点MAC"></el-input>
          </el-form-item>

          <el-form-item label="测点名称：" prop="deviceName">
            <el-input v-model="tempUpdate.deviceName" placeholder="请填写测点名称"></el-input>
          </el-form-item>

          <!-- <el-form-item label="电场数量：" prop="telephone">
            <el-input v-model="tempUpdate.telephone" placeholder="请填写电场数量"></el-input>
          </el-form-item> -->

          <el-form-item label="SIM卡号：" prop="repairUsername">
            <el-input v-model="tempUpdate.repairUsername" placeholder="请填写SIM卡号"></el-input>
          </el-form-item>

          <el-form-item label="SIM卡截止日期：" prop="latitude">
            <el-date-picker
              v-model="tempUpdate.latitude"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择SIM卡截止日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="安装区域：" prop="addressPArr">
            <el-cascader
              placeholder="请选择安装区域"
              v-model="tempUpdate.addressPArr"
              :options="areaList.children"
              :props="{
                label: 'label',
                value: 'label'
              }"
            >
            </el-cascader>
          </el-form-item>

          <el-form-item label="安装地址：" prop="addressC">
            <el-input v-model="tempUpdate.addressC" placeholder="请填写安装地址"></el-input>
          </el-form-item>

          <el-form-item label="设备型号：" prop="deviceModel">
            <el-input v-model="tempUpdate.deviceModel" placeholder="请填写设备型号"></el-input>
          </el-form-item>

          <el-form-item label="测点类型：" prop="deviceType">
            <el-select v-model="tempUpdate.deviceType" placeholder="请选择测点类型" clearable="">
              <el-option
                v-for="item in deviceTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注：" prop="describe">
            <el-input type="textarea" v-model="tempUpdate.describe" placeholder="请填写备注"></el-input>
          </el-form-item>

          <!-- <el-form-item label="测点状态:">
            <el-input v-model="tempUpdate.telephone" disabled=""></el-input>
          </el-form-item>

          <el-form-item label="接入时间：">
            <el-input v-model="tempUpdate.telephone" disabled=""></el-input>
          </el-form-item> -->

          <el-form-item label="">
            <el-button type="success" @click="updateData" :loading="btnLoading">保存</el-button>
            <el-button v-if="deviceList.length > 0" type="warning" @click="delData" :loading="btnLoading">解绑测点
            </el-button>
          </el-form-item>

        </el-form>
      </el-card>
    </template>

    <el-dialog 
      :title="textMap[dialogStatus]" 
      :visible.sync="dialogFormVisible" 
      :close-on-click-modal="false"
      width="800px"
      class="dialog-modal"
    >
      <el-form 
        :rules="rules" 
        ref="dataForm" 
        :model="temp" 
        label-width="140px" 
        style='width:100%;'
        class="clearfix"
      >

        <el-form-item label="测点MAC：" prop="deviceMac">
          <el-input v-model="temp.deviceMac" placeholder="请填写测点MAC"></el-input>
        </el-form-item>

        <el-form-item label="测点名称：" prop="deviceName">
          <el-input v-model="temp.deviceName" placeholder="请填写测点名称"></el-input>
        </el-form-item>

        <!-- <el-form-item label="电场数量：" prop="telephone">
          <el-input v-model="temp.telephone" placeholder="请填写电场数量"></el-input>
        </el-form-item> -->

        <el-form-item label="SIM卡号：" prop="repairUsername">
          <el-input v-model="temp.repairUsername" placeholder="请填写SIM卡号"></el-input>
        </el-form-item>

        <el-form-item label="SIM卡截止日期：" prop="latitude">
          <el-date-picker
            v-model="temp.latitude"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择SIM卡截止日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="安装区域：" prop="addressPArr">
          <el-cascader
            placeholder="请选择安装区域"
            v-model="temp.addressPArr"
            :options="areaList.children"
            :props="{
              label: 'label',
              value: 'label'
            }"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item label="安装地址：" prop="addressC">
          <el-input v-model="temp.addressC" placeholder="请填写安装地址"></el-input>
        </el-form-item>

        <el-form-item label="设备型号：" prop="deviceModel">
          <el-input v-model="temp.deviceModel" placeholder="请填写设备型号"></el-input>
        </el-form-item>

        <el-form-item label="测点类型：" prop="deviceType">
          <el-select v-model="temp.deviceType" placeholder="请选择测点类型" clearable="">
            <el-option
              v-for="item in deviceTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注：" prop="describe">
          <el-input type="textarea" v-model="temp.describe" placeholder="请填写备注"></el-input>
        </el-form-item>

        <!-- <el-form-item label="测点状态:">
          <el-input v-model="temp.telephone" disabled=""></el-input>
        </el-form-item>

        <el-form-item label="接入时间：">
          <el-input v-model="temp.telephone" disabled=""></el-input>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="createData" :loading="btnLoading">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Isp from '@/api/isp'
import { addSave, updateSave, getDetail, getIspDevice, unbindUserInfoDevice } from '@/api/device'
import { mapGetters } from 'vuex'

import areaList from '../../../static/json/area.json'

export default {
  name: 'DeviceSetting',
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  components: {
  },
  data() {
    return {
      btnLoading: false,
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        create: '添加新测点'
      },
      dialogVisible: false,
      temp: {
        deviceType: '', // 请选择测点类型
        deviceMac: '', // 请填写测点MAC
        deviceName: '', // 请填写测点名称
        repairUsername: '', // 请填写SIM卡号
        latitude: '', // 选择SIM卡截止日期

        addressP: '', // 安装地区，省市区
        addressPArr: [], // 安装地区，省市区数组
        addressC: '', // 安装地址
        describe: '', // 备注
        deviceModel: '', // 设备型号

        userId: '', // 单位id
        company: '', // 单位名称
        longitude: '' // 经纬度用半角儿逗号分隔
      },
      rules: {
        deviceType: [
          { required: true, message: '请选择测点类型', trigger: 'change' }
        ],
        deviceMac: [
          { required: true, message: '请填写测点MAC', trigger: 'change' }
        ],
        deviceName: [
          { required: true, message: '请填写测点名称', trigger: 'change' }
        ],
        // repairUsername: [
        //   { required: true, message: '请填写SIM卡号', trigger: 'change' }
        // ],
        // latitude: [
        //   { required: true, message: '选择SIM卡截止日期', trigger: 'change' }
        // ],
        addressPArr: [
          { required: true, message: '请选择安装地区', trigger: 'change' }
        ],
        // addressC: [
        //   { required: true, message: '请填写安装地址', trigger: 'change' }
        // ],
        deviceModel: [
          { required: true, message: '请选择设备型号', trigger: 'change' }
        ]
        // describe: [
        //   { required: true, message: '请填写备注', trigger: 'change' }
        // ]
      },
      tempUpdate: {
        'deviceType': '',
        'deviceMac': '',
        'deviceName': '',
        'repairUsername': '',
        'latitude': '',
        'addressP': '',
        'addressC': '',
        'describe': '',
        'deviceModel': '',
        'userId': '',
        'company': '',
        'longitude': ''
      },
      listLoading: false,
      handleId: '', // 当前操作单位ID
      handleDeviceId: '', // 当前操作设备ID
      baseInfo: [], // 基本信息,
      deviceTypeList: [
        {
          value: '油烟监测',
          label: '油烟监测'
        }
      ],
      // 所在区域数据
      areaList,
      tempUpdateLoading: false,
      deviceList: [] // 设备列表
    }
  },
  watch: {
    // 表单内容体
    temp: {
      handler: function(val, oldVal) {
      },
      deep: true
    }
  },
  created() {
    // 如果是编辑获取id
    const id = this.$route.query.id || ''
    if (id !== '') {
      this.handleId = id
      Isp.getDetail({
        id: this.handleId
      }).then(response => {
        this.baseInfo.push(response.data)
      }).catch(err => {
        err
      })
      // 根据服务商ID获取设备编号和名称
      this.getIspDevice()
    }
  },
  activated() {
  },
  deactivated() {
  },
  methods: {
    //解绑设备。
    delData() {
      //此处添加弹框，表示是否确认解绑。
      this.$confirm('此操作将解绑测点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        unbindUserInfoDevice(this.temp.userId, this.handleDeviceId).then(response => {
          this.btnLoading = false
          this.$notify({
            title: '成功',
            message: '解绑成功',
            type: 'success',
            duration: 2000
          })
        }).catch(err => {
          this.btnLoading = false
          err
        })
      }).catch(() => {
      })
    },
    // 获取设备详情
    getDetail() {
      this.tempUpdateLoading = true
      getDetail({
        deviceMac: this.handleDeviceId
      }).then(response => {
        this.tempUpdate = response.data
        // 所在地区
        if (typeof this.tempUpdate.addressP !== 'undefined' && this.tempUpdate.addressP !== '') {
          this.tempUpdate.addressPArr = this.tempUpdate.addressP.split('/')
        } else {
          this.tempUpdate.addressPArr = []
        }
        this.tempUpdateLoading = false
        console.log(this.tempUpdate)
      }).catch(err => {
        this.tempUpdateLoading = true
        err
      })
    },
    // 选择某一个设备
    changeDeviceId(val) {
      this.getDetail()
    },
    // 根据服务商ID获取设备编号和名称
    getIspDevice() {
      getIspDevice({
        userInfoId: this.handleId
      }).then(response => {
        this.deviceList = response.data || []
        if (this.deviceList.length > 0) {
          this.handleDeviceId = this.deviceList[0].deviceMac
          this.$nextTick(function() {
            this.getDetail()
          })
        }
      }).catch(err => {
        err
      })
    },
    // 重置数据
    resetTemp() {
      this.temp = {
        deviceType: '', // 请选择测点类型
        deviceMac: '', // 请填写测点MAC
        deviceName: '', // 请填写测点名称
        repairUsername: '', // 请填写SIM卡号
        latitude: '', // 选择SIM卡截止日期

        addressP: '', // 安装地区，省市区
        addressPArr: [], // 安装地区，省市区数组
        addressC: '', // 安装地址
        describe: '', // 备注
        deviceModel: '', // 设备型号

        userId: this.baseInfo[0].id, // 单位id
        company: this.baseInfo[0].company, // 单位名称
        longitude: this.baseInfo[0].longitude // 经纬度用半角儿逗号分隔
      }
      return this.temp
    },
    // 创建
    handleCreate(row) {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新建 - 保存
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 所在地区
          if (this.temp.addressPArr.length !== 0) {
            this.temp.addressP = this.temp.addressPArr.join('/')
          } else {
            this.temp.addressP = ''
          }
          this.btnLoading = true
          addSave(this.temp).then(response => {
            // 根据服务商ID获取设备编号和名称
            this.getIspDevice()
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            this.btnLoading = false
            err
          })
        }
      })
    },
    // 编辑 - 保存
    updateData() {
      this.$refs['dataFormUpdate'].validate((valid) => {
        if (valid) {
          // 所在地区
          if (this.tempUpdate.addressPArr.length !== 0) {
            this.tempUpdate.addressP = this.tempUpdate.addressPArr.join('/')
          } else {
            this.tempUpdate.addressP = ''
          }
          this.btnLoading = true
          updateSave(this.tempUpdate).then(response => {
            this.getIspDevice()
            this.btnLoading = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            this.btnLoading = false
            err
          })
        }
      })
    },
    // 返回
    goBack() {
      this.$router.back()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.box-card{
  margin-bottom: 20px;
}
.dialog-modal{
  .el-form-item{
    width: 50%;
    float: left;
  }
}
.up-card{
  .el-form-item{
    width: 33.33%;
    float: left;
  }
}
/deep/ .el-date-editor.el-input{
  width: 100%;
}
</style>
